package com.umcg.monitor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import uk.co.jasonfry.android.tools.ui.SwipeView;
import android.app.Activity;
import android.app.Dialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CacheManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class main extends Activity {
	private DiamondMonitor diamond_monitor;
	private Integer [] dataECG;
	private Integer [] dataPlet;
	private Integer [] dataCO2;
	private Integer [] dataPAW;
	private MaiMonitor mai_monitor;
	private RelativeLayout classic_heartrate;
	private RelativeLayout classic_etco2;
	private RelativeLayout classic_ppeak;
	private RelativeLayout classic_spo2;
	private TextView heartrate;
	private TextView spo2;
	private SeekBar diamond_seekbar;
	private String col_heart = "#00FF00"; // color top graph + nr.
	private String col_co2 = "#FFD700"; // color 2nd graph + nr.
	private String col_ppeak = "#FFFFFF"; // etc
	private String col_paw = "#FF00FF";
	private String col_bp = "#F88017";
	private SwipeView swipeview;
	private WebView classic_webview;
	private WebView diamond_webview;
	private WebView mai_webview;
	private WebView settingsdialog_webview;
	private ClassicMonitor classic_monitor;
	private boolean fresh_data = false;
	private int index = 0;
	private Handler refreshDataHandler = new Handler();
	private Handler refreshPlotHandler = new Handler();
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		setup();
		
		refreshDataHandler.removeCallbacks(initGraphs);
		refreshDataHandler.postDelayed(initGraphs, 500);
		refreshPlotHandler.removeCallbacks(refreshPlot);
		refreshPlotHandler.postDelayed(refreshPlot, 100);
		
		//Zorgt ervoor dat er geen cache wordt gebruikt
		
		try
		{
		  Method m = CacheManager.class.getDeclaredMethod("setCacheDisabled", boolean.class);
		  m.setAccessible(true);
		  m.invoke(null, true);
		}
		catch (Throwable e)
		{
		  Log.i("myapp","Reflection failed", e);
		}
		
	
	}
	
	// Zorgt ervoor dat er niet meerder instanties lopen van het programma.
	@Override
	protected void onDestroy(){
		super.onDestroy();
		refreshDataHandler.removeMessages(0);
		refreshPlotHandler.removeMessages(0);
		
	}
	
	// Handles configuration changes (standaard word onCreate aangeroepen bij draaien toestel)
	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
	    super.onConfigurationChanged(newConfig);
	    setContentView(R.layout.main);
	    setup();
	}

	//Tranformeert dataArrays, wordt aangeroepen in setup();
	private Integer [] transformedData(double multiplier, int yAxis, Integer [] data){
		Integer [] result = new Integer[data.length];
		
		for(int i = 0; i < data.length; i++){
			result[i] = (int)(data[i]*multiplier)+yAxis;
		}
		
		return result;
	}
	private Runnable initGraphs = new Runnable(){
		public void run(){
									
						index = index+30;
						fresh_data = true;
						
			refreshDataHandler.postDelayed(this, 400);
		}
	};
	
	private Runnable refreshPlot = new Runnable(){
		public void run(){
			if(fresh_data == true){
				classic_monitor.plot(dataECG, dataPlet, dataCO2, dataPAW, index);
				//classic_webview.clearCache(true);
				fresh_data = false;
			}
			//spo2.setText("" + fresh_data);
			refreshPlotHandler.postDelayed(this, 10);
		}
	};
	
	private void plotStuff() {
		//for(int i = 0; i < (dataECG.length - 33) ; i=i+33){
			if(!paused){
				try{
					if(fresh_data == true){
						classic_monitor.plot(dataECG, dataPlet, dataCO2, dataPAW, index);
						
						fresh_data = false;
					}
					
					//debugger.setText("");
					
					Thread.sleep(10);
				}catch(InterruptedException ex){
					ex.printStackTrace();
				}
			}
		//}
	}
	
	private void refreshData(){
		for(int i = 0; i <(dataECG.length -33); i=i+33){
			if(!paused){
				try{
					index = i;
					heartrate.setText("hoi");
					fresh_data = true;
					
					Thread.sleep(500);
				}catch(InterruptedException ex){
					ex.printStackTrace();
				}
			}
		}

	}
	
	boolean paused = false;

	@Override
	protected void onPause() {
		paused = true;
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		paused = false;
	}

	private void setup() {
		// SwipeView
		swipeview = (SwipeView) findViewById(R.id.swipe_view);
		swipeview.scrollToPage(1);
		
		// DiamondMonitor
		diamond_webview = (WebView) findViewById(R.id.webViewDiamond);
		
		diamond_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		//diamond_seekbar = (SeekBar) findViewById(R.id.seekBarDiamond);
		diamond_monitor = new DiamondMonitor(diamond_webview);

		// ClassicMonitor
		classic_webview = (WebView) findViewById(R.id.webViewClassic);
		
		classic_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		
		
		classic_heartrate = (RelativeLayout) findViewById(R.id.relativeLayoutHeartRate);
		classic_ppeak = (RelativeLayout) findViewById(R.id.relativeLayoutPPeak);
		classic_spo2 = (RelativeLayout) findViewById(R.id.relativeLayoutSPO2);
		classic_etco2 = (RelativeLayout) findViewById(R.id.relativeLayoutEtCO2);
		heartrate = (TextView) findViewById(R.id.heartRate);
		spo2 = (TextView) findViewById(R.id.SPO2);
		dataECG = 	readFile("ECG.txt");
		dataPlet = 	readFile("Plet.txt");
		dataCO2 = 	readFile("CO2.txt");
		dataPAW = 	readFile("PAW.txt");
		
		dataECG = transformedData(3, 8000, dataECG);
		dataPlet = transformedData(0.5, 5000, dataPlet);
		dataCO2 = transformedData(1,3000, dataCO2);
		dataPAW = transformedData(2.5,0, dataPAW);
		
		classic_webview = (WebView) findViewById(R.id.webViewClassic); // Contains a graph
		classic_monitor = new ClassicMonitor(classic_webview, col_heart, col_co2, col_ppeak, col_paw, dataECG, dataPlet, dataCO2, dataPAW);
		classic_heartrate.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//onPause();
				SettingsDialog dialog = new SettingsDialog(new Dialog(main.this));
				dialog.setTitle("Heart Rate");
				dialog.show();	
			}
		});
		classic_etco2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//onPause();
				SettingsDialog dialog = new SettingsDialog(new Dialog(main.this));
				dialog.setTitle("etCO2");
				dialog.show();	
			}
		});
		classic_ppeak.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//onPause();
				SettingsDialog dialog = new SettingsDialog(new Dialog(main.this));
				dialog.setTitle("Ppeak");
				dialog.show();	
			}
		});
		classic_spo2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//onPause();
				SettingsDialog dialog = new SettingsDialog(new Dialog(main.this));
				dialog.setTitle("SpO2");
				dialog.show();	
			}
		});
		
		// SettingsDialog
		settingsdialog_webview = (WebView) findViewById(R.id.webViewSettingsDialog);
		//settingsdialog_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		// MAI monitor
		mai_webview = (WebView) findViewById(R.id.webViewMAI);
		mai_monitor = new MaiMonitor(mai_webview);
		
		// DiamondMonitor
		//diamond_webview = (WebView) findViewById(R.id.webViewDiamond);
		//diamond_monitor = new DiamondMonitor(diamond_webview);
		
		
	}
	
	/*
	 * Optiemenu (hardware menuknop)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	/*
	 * Optiemenu (hardware menuknop)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.kleur:
			Toast.makeText(this, "kleuren", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.info:
			Toast.makeText(this, "Copyright T.Doesburg & P.Moes", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.hartfrequentie:
			SettingsDialog dialog = new SettingsDialog(new Dialog(main.this));
			dialog.setTitle("Heart Rate");
			dialog.show();
			return true;
		case R.id.spo2:
			SettingsDialog dialog2 = new SettingsDialog(new Dialog(main.this));
			dialog2.setTitle("SPO2");
			dialog2.show();
			return true;
		case R.id.co2:
			SettingsDialog dialog3 = new SettingsDialog(new Dialog(main.this));
			dialog3.setTitle("etCO2");
			dialog3.show();
			return true;
		case R.id.paw:
			SettingsDialog dialog4 = new SettingsDialog(new Dialog(main.this));
			dialog4.setTitle("Ppeak");
			dialog4.show();
			return true;
		case R.id.exit:
			refreshDataHandler.removeMessages(0);
			refreshPlotHandler.removeMessages(0);
			finish();
		

		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	/** 
     * reads a file with numbers and returns an array with floats 
     */ 
	private Integer [] readFile(String file) { 
		BufferedReader br = null; 
		List<Integer> dataList = new ArrayList<Integer>(); 
		try { 
			br = new BufferedReader(new InputStreamReader(getAssets().open(file))); // throwing a FileNotFoundException? 
			String number; 
			while ((number = br.readLine()) != null) 
				dataList.add(Integer.valueOf(number.trim()).intValue()); 
		} catch (IOException e) { 
			e.printStackTrace();
		} finally { 
			try { 
				br.close(); // stop reading 
			} catch (IOException ex) { 
				ex.printStackTrace(); 
			} 
		} 
		Integer[] data = new Integer[dataList.size()]; 
		dataList.toArray(data); 
		//Toast.makeText(this, data[1].toString(), Toast.LENGTH_SHORT).show();
		return data; 
	}
	

}